package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.CustomerUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.RsaUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ICustomerService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 注册校验方法
 */
@Component
public class CustomerRegisterService {
    @Autowired
    private ICustomerService userService;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        CustomerUser sysUser = new CustomerUser();
        sysUser.setUserName(username);

        if (StringUtils.isEmpty(username)) {
            msg = "Username cannot be empty";
        } else if (StringUtils.isEmpty(password)) {
            msg = "Password cannot be empty";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "Username length must be between 2 and 20 characters";
        } else if (!userService.checkUserNameUnique(sysUser)) {
            msg = "Failed to save user '" + username + "', username already exists";
        } else {
            sysUser.setEmail(registerBody.getEmail());
//            RsaUtils.encryptByPrivateKey(password)
            try {
                password = RsaUtils.decryptByPrivateKey(password);
                String enPassword = SecurityUtils.encryptPassword(password);
                sysUser.setPassword(enPassword);
                boolean regFlag = userService.registerUser(sysUser);
                if (!regFlag) {
                    msg = "Registration failed, please contact system administrator";
                } else {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                }
            } catch (Exception e) {

            }
        }
        return msg;
    }


}
